<script setup>
import { ref, onMounted } from 'vue'
import { listAdminDoctors, createAdminDoctor, listDepartments, listPositions } from '../../api/admin'
import { ElMessage } from 'element-plus'

const list = ref([])
const total = ref(0)
const query = ref({ name: '', positionId: '', departmentId: '', page: 1, size: 10 })
const loading = ref(false)

const deptOptions = ref([])
const posOptions = ref([])
const deptMap = ref({})
const posMap = ref({})

const dialogVisible = ref(false)
const formRef = ref()
const saving = ref(false)
const form = ref({ name: '', gender: '男', phone: '', departmentId: '', positionId: '', intro: '', password: '' })

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/i, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { min: 6, message: '初始密码至少6位（可选）', trigger: 'blur' }
  ]
}

const fetchList = async () => {
  loading.value = true
  try {
    const data = await listAdminDoctors({ name: query.value.name || undefined, positionId: query.value.positionId || undefined, departmentId: query.value.departmentId || undefined, page: query.value.page, size: query.value.size })
    list.value = data.list || []
    total.value = data.total || 0
  } finally { loading.value = false }
}

const fetchOptions = async () => {
  const [dpt, pos] = await Promise.all([
    listDepartments({ page: 1, size: 200 }).catch(() => ({ list: [] })),
    listPositions({ page: 1, size: 200 }).catch(() => ({ list: [] }))
  ])
  deptOptions.value = (dpt.list || []).map(it => ({ label: it.departmentName, value: it.departmentId }))
  posOptions.value = (pos.list || []).map(it => ({ label: it.positionName, value: it.positionId }))
  deptMap.value = Object.fromEntries(deptOptions.value.map(it => [it.value, it.label]))
  posMap.value = Object.fromEntries(posOptions.value.map(it => [it.value, it.label]))
}

const openCreate = () => { form.value = { name: '', gender: '男', phone: '', departmentId: '', positionId: '', intro: '', password: '' }; dialogVisible.value = true }

const submit = async () => {
  await formRef.value?.validate(async (valid) => {
    if (!valid) return
    saving.value = true
    try {
      const payload = { name: form.value.name, gender: form.value.gender || undefined, phone: form.value.phone, departmentId: form.value.departmentId || undefined, positionId: form.value.positionId || undefined, intro: form.value.intro || undefined, password: form.value.password || undefined }
      await createAdminDoctor(payload)
      ElMessage.success('新增医生成功')
      dialogVisible.value = false
      fetchList()
    } finally { saving.value = false }
  })
}

onMounted(async () => { await fetchOptions(); await fetchList() })
</script>

<template>
  <el-card>
    <div class="header">
      <h3>医生管理</h3>
      <div class="header-actions">
        <el-button @click="fetchList">刷新</el-button>
        <el-button type="primary" @click="openCreate">新增医生</el-button>
      </div>
    </div>
    <el-form :inline="true" :model="query" class="mb-2">
      <el-form-item label="姓名"><el-input v-model="query.name" /></el-form-item>
      <el-form-item label="职称">
        <el-select v-model="query.positionId" style="width:180px" clearable placeholder="选择职称">
          <el-option v-for="p in posOptions" :key="p.value" :label="p.label" :value="p.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="科室">
        <el-select v-model="query.departmentId" style="width:180px" clearable placeholder="选择科室">
          <el-option v-for="d in deptOptions" :key="d.value" :label="d.label" :value="d.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query.page=1;fetchList()">查询</el-button>
        <el-button @click="query={ name:'', positionId:'', departmentId:'', page:1, size: query.size }; fetchList()">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" v-loading="loading" style="width:100%">
      <el-table-column prop="doctorId" label="医生ID" width="90" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column label="职称">
        <template #default="{ row }">
          <el-tag v-if="posMap[row.positionId]" type="info">{{ posMap[row.positionId] }}</el-tag>
          <span v-else>{{ row.positionId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="科室">
        <template #default="{ row }">
          <el-tag v-if="deptMap[row.departmentId]" type="success">{{ deptMap[row.departmentId] }}</el-tag>
          <span v-else>{{ row.departmentId }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="intro" label="简介" />
      <template #empty>
        <el-empty description="暂无医生数据，尝试调整筛选或点击右上角新增医生" />
      </template>
    </el-table>
    <el-pagination class="mt-2" background layout="total, prev, pager, next" :total="total" :page-size="query.size" :current-page="query.page" @current-change="(p)=>{query.page=p;fetchList()}" />
  </el-card>

  <el-dialog v-model="dialogVisible" title="新增医生" width="560px">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="姓名" prop="name"><el-input v-model="form.name" placeholder="请输入姓名" /></el-form-item>
      <el-form-item label="性别"><el-radio-group v-model="form.gender"><el-radio label="男">男</el-radio><el-radio label="女">女</el-radio></el-radio-group></el-form-item>
      <el-form-item label="手机号" prop="phone"><el-input v-model="form.phone" placeholder="11位手机号" /></el-form-item>
      <el-form-item label="科室">
        <el-select v-model="form.departmentId" style="width:220px" placeholder="选择科室" clearable>
          <el-option v-for="d in deptOptions" :key="d.value" :label="d.label" :value="d.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="职称">
        <el-select v-model="form.positionId" style="width:220px" placeholder="选择职称" clearable>
          <el-option v-for="p in posOptions" :key="p.value" :label="p.label" :value="p.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="简介"><el-input v-model="form.intro" type="textarea" :rows="3" placeholder="医生简介（可选）" /></el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" :loading="saving" @click="submit">提交</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.header{ display:flex; justify-content:space-between; align-items:center; }
.header-actions{ display:flex; gap:8px; }
.mb-2{ margin-bottom:12px; }
.mt-2{ margin-top:12px; }
</style>